--
-- Created by IntelliJ IDEA.
-- User: dz
-- Date: 2017/3/3
-- Time: 10:49
-- To change this template use File | Settings | File Templates.
--
local userId = ARGV[1]; --用户id
local sequence = ARGV[2]; --最近一次看的id
local operation = ARGV[3]; --操作，向上滚动还是向下滚动

--取出个人的时间线
local timelineName = userId .. ':tls';

local timelineArray = {};
local momentIds;
--数组
if (operation == 0 or operation == "0") then
    momentIds = redis.call("ZRANGEBYSCORE", timelineName, "-inf", sequence, "limit", "0", "10");
else
    momentIds = redis.call("ZRANGEBYSCORE", timelineName, sequence, "+inf", "limit", "0", "10");
end
if momentIds then
    for k, momentId in pairs(momentIds) do
        local momentJson = redis.call("hget", "moments", momentId);
        local seenCount = redis.call("hget", momentId, "seenCount");
        local likedCount = redis.call("hget", momentId, "likedCount");
        local commentsCount = redis.call("hget", momentId, "commentsCount");
        local giftsCount = redis.call("hget", momentId, "giftsCount");
        if momentJson then
            local moment = cjson.decode(momentJson);
            if seenCount then
                moment['seenCount'] = seenCount;
            else
                moment['seenCount'] = "0";
            end
            if likedCount then
                moment['likedCount'] = likedCount;
            else
                moment['likedCount'] = "0";
            end
            if commentsCount then
                moment['commentsCount'] = commentsCount;
            else
                moment['commentsCount'] = "0";
            end
            if giftsCount then
                moment['giftsCount'] = giftsCount;
            else
                moment['giftsCount'] = "0";
            end
            timelineArray[k] = cjson.encode(moment);
        else
            local emptyMoment = {};
            emptyMoment['momentId'] = momentId;
            emptyMoment['userId'] = -1;
            if seenCount then
                emptyMoment['seenCount'] = seenCount;
            else
                emptyMoment['seenCount'] = "0";
            end
            if likedCount then
                emptyMoment['likedCount'] = likedCount;
            else
                emptyMoment['likedCount'] = "0";
            end
            if commentsCount then
                emptyMoment['commentsCount'] = commentsCount;
            else
                emptyMoment['commentsCount'] = "0";
            end
            if giftsCount then
                emptyMoment['giftsCount'] = giftsCount;
            else
                emptyMoment['giftsCount'] = "0";
            end
            timelineArray[k] = cjson.encode(emptyMoment);
        end
    end
end
return timelineArray;